"""
采购申请模型
"""
from datetime import datetime
from app import db

class PurchaseApplication(db.Model):
    """采购申请表"""
    __tablename__ = 'mx_purchase_applications'

    id = db.Column(db.Integer, primary_key=True)
    applicant_id = db.Column(db.String(50), db.ForeignKey('mx_employees.employee_id'), nullable=False)
    purchase_amount = db.Column(db.Float, nullable=False, comment='采购总金额')
    items_json = db.Column(db.Text, nullable=False, comment='采购明细(JSON字符串)')
    status = db.Column(db.String(20), default='pending', comment='状态: pending, approved, rejected')
    project_id = db.Column(db.Integer, nullable=True, comment='所属项目ID，用于成本统计')
    process_instance_id = db.Column(db.String(100), comment='Flowable流程实例ID')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    applicant = db.relationship('Employee', backref='purchase_applications')

    def to_dict(self):
        return {
            'id': self.id,
            'applicant_id': self.applicant_id,
            'applicant_name': self.applicant.name if self.applicant else None,
            'purchase_amount': self.purchase_amount,
            'items': self.items_json,
            'status': self.status,
            'project_id': self.project_id,
            'process_instance_id': self.process_instance_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
